<template>
  <view :class="['custom-form', formClass]" :style="[formStyle, customStyle]">
    <!-- 表单头部 -->
    <view v-if="showHeader || $slots.header" class="form-header">
      <slot name="header">
        <view v-if="title" class="form-title">
          <text class="title-text">{{ title }}</text>
          <text v-if="subtitle" class="subtitle-text">{{ subtitle }}</text>
        </view>
      </slot>
    </view>

    <!-- 表单内容 -->
    <view class="form-content">
      <slot>
        <!-- 表单项 -->
        <view 
          v-for="(field, index) in fields" 
          :key="getFieldKey(field, index)"
          :class="['form-item', fieldClass, { 'form-item--disabled': field.disabled }]"
          :style="getFieldStyle(field, index)"
        >
          <!-- 标签 -->
          <view v-if="field.label" class="form-label">
            <text class="label-text" :class="{ 'label-required': field.required }">
              {{ field.label }}
            </text>
          </view>

          <!-- 输入控件 -->
          <view class="form-control">
            <!-- 文本输入 -->
            <uni-input
              v-if="field.type === 'text' || field.type === 'textarea'"
              :value="field.value"
              :placeholder="field.placeholder"
              :disabled="field.disabled"
              :maxlength="field.maxlength"
              :type="field.type === 'textarea' ? 'textarea' : 'text'"
              :auto-height="field.type === 'textarea'"
              :style="field.inputStyle"
              @input="handleInput(field, $event)"
              @blur="handleBlur(field, $event)"
              @focus="handleFocus(field, $event)"
            />

            <!-- 数字输入 -->
            <uni-input
              v-else-if="field.type === 'number'"
              :value="field.value"
              :placeholder="field.placeholder"
              :disabled="field.disabled"
              type="number"
              :style="field.inputStyle"
              @input="handleInput(field, $event)"
              @blur="handleBlur(field, $event)"
              @focus="handleFocus(field, $event)"
            />

            <!-- 密码输入 -->
            <uni-input
              v-else-if="field.type === 'password'"
              :value="field.value"
              :placeholder="field.placeholder"
              :disabled="field.disabled"
              :password="!field.showPassword"
              :style="field.inputStyle"
              @input="handleInput(field, $event)"
              @blur="handleBlur(field, $event)"
              @focus="handleFocus(field, $event)"
            >
              <template #suffix>
                <text 
                  :class="['iconfont-v2', field.showPassword ? 'icon-yanjing' : 'icon-yanjing-biyan']"
                  @click="togglePassword(field)"
                ></text>
              </template>
            </uni-input>

            <!-- 选择器 -->
            <view
              v-else-if="field.type === 'select'"
              :class="['form-select', { 'form-select--disabled': field.disabled }]"
              @click="handleSelect(field)"
            >
              <text :class="['select-text', { 'select-placeholder': !field.value }]">
                {{ field.value || field.placeholder }}
              </text>
              <text class="iconfont-v2 icon-xiajiantou select-arrow"></text>
            </view>

            <!-- 日期选择器 -->
            <view
              v-else-if="field.type === 'date'"
              :class="['form-date', { 'form-date--disabled': field.disabled }]"
              @click="handleDateSelect(field)"
            >
              <text :class="['date-text', { 'date-placeholder': !field.value }]">
                {{ field.value || field.placeholder }}
              </text>
              <text class="iconfont-v2 icon-rili date-icon"></text>
            </view>

            <!-- 开关 -->
            <switch
              v-else-if="field.type === 'switch'"
              :checked="field.value"
              :disabled="field.disabled"
              :color="field.switchColor || '#ED6567'"
              @change="handleSwitch(field, $event)"
            />

            <!-- 单选框组 -->
            <view v-else-if="field.type === 'radio'" class="form-radio-group">
              <view
                v-for="(option, optionIndex) in field.options"
                :key="optionIndex"
                :class="['radio-option', { 'radio-option--selected': field.value === option.value }]"
                @click="handleRadio(field, option)"
              >
                <text :class="['radio-icon', field.value === option.value ? 'icon-dagou' : 'icon-yuanxing-weigouxuan']"></text>
                <text class="radio-text">{{ option.label }}</text>
              </view>
            </view>

            <!-- 复选框组 -->
            <view v-else-if="field.type === 'checkbox'" class="form-checkbox-group">
              <view
                v-for="(option, optionIndex) in field.options"
                :key="optionIndex"
                :class="['checkbox-option', { 'checkbox-option--selected': field.value && field.value.includes(option.value) }]"
                @click="handleCheckbox(field, option)"
              >
                <text :class="['checkbox-icon', field.value && field.value.includes(option.value) ? 'icon-dagou' : 'icon-fangxing-weigouxuan']"></text>
                <text class="checkbox-text">{{ option.label }}</text>
              </view>
            </view>

            <!-- 自定义插槽 -->
            <slot v-else-if="field.type === 'slot'" :name="field.slotName" :field="field" :index="index" />
          </view>

          <!-- 错误提示 -->
          <view v-if="field.error" class="form-error">
            <text class="error-text">{{ field.error }}</text>
          </view>

          <!-- 帮助文本 -->
          <view v-if="field.help" class="form-help">
            <text class="help-text">{{ field.help }}</text>
          </view>
        </view>
      </slot>
    </view>

    <!-- 表单底部 -->
    <view v-if="showFooter || $slots.footer" class="form-footer">
      <slot name="footer">
        <view v-if="submitText" class="form-submit">
          <button
            :class="['submit-button', submitButtonClass]"
            :style="submitButtonStyle"
            :disabled="submitDisabled"
            @click="handleSubmit"
          >
            {{ submitText }}
          </button>
        </view>
      </slot>
    </view>
  </view>
</template>

<script>
/**
 * 通用表单组件
 * @description 通用的表单组件，支持多种输入类型和验证
 * @author 系统
 * @date 2024
 */

export default {
  name: 'CustomForm',
  props: {
    // 表单数据
    model: {
      type: Object,
      default: () => ({})
    },
    // 表单字段配置
    fields: {
      type: Array,
      default: () => []
    },
    // 表单标题
    title: {
      type: String,
      default: ''
    },
    // 副标题
    subtitle: {
      type: String,
      default: ''
    },
    // 提交按钮文本
    submitText: {
      type: String,
      default: '提交'
    },
    // 是否显示头部
    showHeader: {
      type: Boolean,
      default: false
    },
    // 是否显示底部
    showFooter: {
      type: Boolean,
      default: true
    },
    // 是否禁用提交
    submitDisabled: {
      type: Boolean,
      default: false
    },
    // 表单变体: 'default' | 'inline' | 'vertical'
    variant: {
      type: String,
      default: 'default',
      validator: value => ['default', 'inline', 'vertical'].includes(value)
    },
    // 自定义类名
    formClass: {
      type: String,
      default: ''
    },
    // 表单项类名
    fieldClass: {
      type: String,
      default: ''
    },
    // 提交按钮类名
    submitButtonClass: {
      type: String,
      default: ''
    },
    // 自定义样式
    customStyle: {
      type: Object,
      default: () => ({})
    },
    // 表单样式
    formStyle: {
      type: Object,
      default: () => ({})
    },
    // 提交按钮样式
    submitButtonStyle: {
      type: Object,
      default: () => ({})
    },
    // 验证规则
    rules: {
      type: Object,
      default: () => ({})
    }
  },
  methods: {
    // 获取字段唯一标识
    getFieldKey(field, index) {
      return field.key || field.name || index
    },
    
    // 获取字段样式
    getFieldStyle(field, index) {
      return field.style || {}
    },
    
    // 处理输入事件
    handleInput(field, event) {
      const value = event.detail.value
      this.updateFieldValue(field, value)
      this.$emit('field-input', field, value)
    },
    
    // 处理失焦事件
    handleBlur(field, event) {
      this.validateField(field)
      this.$emit('field-blur', field, event)
    },
    
    // 处理聚焦事件
    handleFocus(field, event) {
      this.$emit('field-focus', field, event)
    },
    
    // 处理选择事件
    handleSelect(field) {
      if (field.disabled) return
      this.$emit('field-select', field)
    },
    
    // 处理日期选择
    handleDateSelect(field) {
      if (field.disabled) return
      this.$emit('field-date-select', field)
    },
    
    // 处理开关变化
    handleSwitch(field, event) {
      const value = event.detail.value
      this.updateFieldValue(field, value)
      this.$emit('field-switch', field, value)
    },
    
    // 处理单选框选择
    handleRadio(field, option) {
      if (field.disabled) return
      this.updateFieldValue(field, option.value)
      this.$emit('field-radio', field, option)
    },
    
    // 处理复选框选择
    handleCheckbox(field, option) {
      if (field.disabled) return
      const currentValue = field.value || []
      const newValue = currentValue.includes(option.value)
        ? currentValue.filter(v => v !== option.value)
        : [...currentValue, option.value]
      this.updateFieldValue(field, newValue)
      this.$emit('field-checkbox', field, option, newValue)
    },
    
    // 切换密码显示
    togglePassword(field) {
      field.showPassword = !field.showPassword
    },
    
    // 更新字段值
    updateFieldValue(field, value) {
      field.value = value
      this.$emit('update:model', { ...this.model, [field.name]: value })
    },
    
    // 验证字段
    validateField(field) {
      const rules = this.rules[field.name]
      if (!rules) return true
      
      let error = ''
      
      // 必填验证
      if (rules.required && (!field.value || field.value === '')) {
        error = rules.message || `${field.label}不能为空`
      }
      
      // 长度验证
      if (rules.minLength && field.value && field.value.length < rules.minLength) {
        error = rules.message || `${field.label}长度不能少于${rules.minLength}位`
      }
      
      if (rules.maxLength && field.value && field.value.length > rules.maxLength) {
        error = rules.message || `${field.label}长度不能超过${rules.maxLength}位`
      }
      
      // 正则验证
      if (rules.pattern && field.value && !rules.pattern.test(field.value)) {
        error = rules.message || `${field.label}格式不正确`
      }
      
      field.error = error
      return !error
    },
    
    // 验证整个表单
    validateForm() {
      let isValid = true
      this.fields.forEach(field => {
        if (!this.validateField(field)) {
          isValid = false
        }
      })
      return isValid
    },
    
    // 处理提交
    handleSubmit() {
      if (this.submitDisabled) return
      
      if (this.validateForm()) {
        this.$emit('submit', this.model)
      } else {
        this.$emit('validate-error')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-form {
  background: white;
  border-radius: 24rpx;
  overflow: hidden;

  // 变体样式
  &--inline {
    .form-item {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .form-label {
        width: 200rpx;
        margin-right: 20rpx;
        margin-bottom: 0;
      }

      .form-control {
        flex: 1;
      }
    }
  }

  &--vertical {
    .form-item {
      .form-label {
        margin-bottom: 16rpx;
      }
    }
  }

  // 表单头部
  .form-header {
    padding: 30rpx;
    border-bottom: 2rpx solid #f5f5f5;

    .form-title {
      .title-text {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 8rpx;
      }

      .subtitle-text {
        font-size: 24rpx;
        color: #666;
        display: block;
      }
    }
  }

  // 表单内容
  .form-content {
    .form-item {
      padding: 30rpx;
      border-bottom: 2rpx solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      &--disabled {
        opacity: 0.6;
        pointer-events: none;
      }

      // 表单标签
      .form-label {
        margin-bottom: 20rpx;

        .label-text {
          font-size: 28rpx;
          font-weight: 500;
          color: #333;
          display: block;

          &.label-required::before {
            content: '*';
            color: #ff4d4f;
            margin-right: 8rpx;
          }
        }
      }

      // 表单控件
      .form-control {
        // 选择器
        .form-select {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 24rpx 32rpx;
          background: #f8f9fa;
          border-radius: 16rpx;
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover:not(.form-select--disabled) {
            background: #e9ecef;
          }

          &--disabled {
            opacity: 0.6;
            cursor: not-allowed;
          }

          .select-text {
            font-size: 28rpx;
            color: #333;

            &.select-placeholder {
              color: #999;
            }
          }

          .select-arrow {
            font-size: 24rpx;
            color: #ccc;
            transition: transform 0.3s ease;
          }

          &:hover .select-arrow {
            transform: rotate(180deg);
          }
        }

        // 日期选择器
        .form-date {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 24rpx 32rpx;
          background: #f8f9fa;
          border-radius: 16rpx;
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover:not(.form-date--disabled) {
            background: #e9ecef;
          }

          &--disabled {
            opacity: 0.6;
            cursor: not-allowed;
          }

          .date-text {
            font-size: 28rpx;
            color: #333;

            &.date-placeholder {
              color: #999;
            }
          }

          .date-icon {
            font-size: 24rpx;
            color: #ED6567;
          }
        }

        // 单选框组
        .form-radio-group {
          display: flex;
          flex-wrap: wrap;
          gap: 20rpx;

          .radio-option {
            display: flex;
            align-items: center;
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              opacity: 0.8;
            }

            &--selected {
              .radio-icon {
                color: #ED6567;
              }

              .radio-text {
                color: #ED6567;
                font-weight: 500;
              }
            }

            .radio-icon {
              font-size: 32rpx;
              color: #ccc;
              margin-right: 12rpx;
              transition: color 0.3s ease;
            }

            .radio-text {
              font-size: 28rpx;
              color: #333;
              transition: all 0.3s ease;
            }
          }
        }

        // 复选框组
        .form-checkbox-group {
          display: flex;
          flex-wrap: wrap;
          gap: 20rpx;

          .checkbox-option {
            display: flex;
            align-items: center;
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              opacity: 0.8;
            }

            &--selected {
              .checkbox-icon {
                color: #ED6567;
              }

              .checkbox-text {
                color: #ED6567;
                font-weight: 500;
              }
            }

            .checkbox-icon {
              font-size: 32rpx;
              color: #ccc;
              margin-right: 12rpx;
              transition: color 0.3s ease;
            }

            .checkbox-text {
              font-size: 28rpx;
              color: #333;
              transition: all 0.3s ease;
            }
          }
        }
      }

      // 错误提示
      .form-error {
        margin-top: 16rpx;

        .error-text {
          font-size: 24rpx;
          color: #ff4d4f;
        }
      }

      // 帮助文本
      .form-help {
        margin-top: 16rpx;

        .help-text {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }

  // 表单底部
  .form-footer {
    padding: 30rpx;
    border-top: 2rpx solid #f5f5f5;

    .form-submit {
      .submit-button {
        width: 100%;
        background: #ED6567;
        color: white;
        border: none;
        border-radius: 44rpx;
        padding: 24rpx;
        font-size: 28rpx;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover:not(:disabled) {
          background: #d55a54;
        }

        &:active:not(:disabled) {
          transform: scale(0.98);
        }

        &:disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }
      }
    }
  }
}
</style>
